# -*- coding: UTF-8 -*-

from utils.log_util.LoggerUtil import get_logger
import json
from utils.requests_util import RequestsUtil
import time
from utils.date_util import DateUtil
import pymongo

log = get_logger(__name__)


class IPUtil:

    ip_str = ''
    json_text = {}
    exist_ip_list = []
    conn = None
    db = None

    def init_objs(self):
        if self.conn is None:
            self.conn = self.get_mongo_conn()
        if self.db is None:
            self.db = self.get_mongo_db(self.conn)
        if len(self.exist_ip_list) == 0:
            self.exist_ip_list = self.ip_str_to_ip_list(self.get_ip_info_list_from_mongo())

    def __del__(self):
        if self.conn is not None:
            self.conn.close()

    def find(self, ip_addr, **kwargs):
        self.init_objs()
        ip_info = {}
        if self.exist_ip_list.__contains__(ip_addr):
            ip_info_list = self.db[self.parse_ip_str(ip_addr)].find()
            ip_info = ip_info_list[ip_info_list.count() - 1]
        else:
            ip_info = self.get_ip_from(ip_addr)
            self.save_to_mongo()
        if kwargs.get('last_one') is not None and kwargs.get('last_one'):
            self.conn.close()
        return ip_info


    def get_ip_from(self, remote_addr):
        self.ip_str = "IP_" + remote_addr.replace(".", "_")
        count = 0
        # print(text.text)
        while True:
            try:
                request_url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + remote_addr
                text = RequestsUtil.getRequest(request_url)
                if text.status_code != 200:
                    time.sleep(1)
                    continue
                self.json_text = json.loads(text.text).get('data')
            except:
                time.sleep(1)
                # print(remote_addr + str(text) + str(text.text))
                count += 1
                if count >= 3:
                    return {}
            if len(self.json_text) != 0:
                break
        self.json_text['query_time'] = DateUtil.getNow()
        self.json_text['from_str'] = self.json_text.get('country') + self.json_text.get('area') + self.json_text.get('region') \
                                + self.json_text.get('city') + self.json_text.get('county') + self.json_text.get('isp')
        return self.json_text

    def get_mongo_conn(self):
        return pymongo.MongoClient("mongodb://agno.top:27017")

    def get_mongo_db(self, conn):
        db = conn.ip_info
        return db

    def save_to_mongo(self):
        if len(self.json_text) != 0:
            self.db[self.ip_str].insert_one(self.json_text)

    def get_ip_info_list_from_mongo(self):
        return self.db.list_collection_names()

    def ip_str_to_ip_list(self, ip_str_list):
        ip_list = []
        for e in ip_str_list:
            ip_list.append(str(e).replace("IP_", "").replace("_", "."))
        return ip_list

    def parse_ip_str(self, remote_addr):
        return "IP_" + remote_addr.replace(".", "_")